package com.sihai.ehr.web.action.ajax;

import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

/**
 * @author pippo
 * @since 2010-8-30-14:39:57
 */
public class AjaxCallback {

	public static AjaxCallback success() {
		return success(null, null);
	}

	public static AjaxCallback failure() {
		return failure(null, null);
	}

	public static AjaxCallback success(String message, Object result) {
		AjaxCallback callback = new AjaxCallback();
		callback.success = true;
		callback.message = message;
		callback.result = result;
		return callback;
	}
	
	// added by henry --->add the real file name
	public static AjaxCallback success(String message, Object result,String realName) {
		AjaxCallback callback = new AjaxCallback();
		callback.success = true;
		callback.message = message;
		callback.result = result;
		callback.realName = realName;
		return callback;
	}

	public static AjaxCallback failure(String message, Object result) {
		AjaxCallback callback = new AjaxCallback();
		callback.success = false;
		callback.message = message;
		callback.result = result;
		return callback;
	}

	private static JSONProcessor default_processor = new DefaultJSONProcessor();

	public void flush(HttpServletResponse resp) throws IOException {
		this.flush(resp, default_processor);
	}

	public void flush(HttpServletResponse resp, JSONProcessor processor)
			throws IOException {
		String strProcessor = processor.process(this);
		
		//用于中文乱码问题
		resp.setCharacterEncoding("utf-8");   
		resp.setContentType("text/html;charset=utf-8");   
		resp.setLocale(Locale.CHINESE);  
	
		// strProcessor = strProcessor.replaceAll("\r\n", "");
		resp.getOutputStream().write(strProcessor.getBytes());
	}

	private Boolean success;

	private String message;

	private Object result;
	
	private String realName;

	public boolean isSuccess() {
		return Boolean.TRUE.equals(this.success);
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String getMessage() {
		return message != null ? message : "";
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Object getResult() {
		return result != null ? result : "";
	}

	public void setResult(Object result) {
		this.result = result;
	}
	
	public String getRealName() {
		return realName;
	}
	
	public void setRealName(String realName) {
		this.realName = realName;
	}

	public interface JSONProcessor {

		String process(AjaxCallback callback);

	}

	private static class DefaultJSONProcessor implements JSONProcessor {

		@Override
		public String process(AjaxCallback callback) {
			return JSONObject.fromObject(callback).toString();
		}

	}

}
